package com.sywb.chuangyebao.contract;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.czt.mp3recorder.MP3Recorder;
import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;

import org.bining.footstone.log.Logger;
import org.bining.footstone.mvp.IView;
import org.bining.footstone.presenter.BasePresenter;
import org.bining.footstone.rxjava.rxbus.RxBus;
import org.bining.footstone.utils.ToastUtils;

import java.io.IOException;
import java.util.HashMap;

public interface AskAudioContract {

    interface AskAudioView extends IView {

        TextView getTvAudioTime();

        void dismiss();
    }

    class Presenter extends BasePresenter<AskAudioView> {

        private MP3Recorder mp3Recorder;

        private int recLen = 0;
        private Handler handler = new Handler();
        private Runnable runnable = new Runnable() {
            @SuppressLint("SetTextI18n")
            @Override
            public void run() {
                String tip = "0:";
                recLen++;
                if (recLen == 60) {
                    ToastUtils.show(mActivity, R.string.audio60);
                    afterRecord();
                    return;
                }
                mView.getTvAudioTime().setText(tip + (recLen > 9 ? String.valueOf(recLen) : "0" + recLen));

                Logger.e("volume:" + mp3Recorder.getRealVolume());

                handler.postDelayed(this, 1000);
            }
        };

        @Override
        public void onDestroy() {
            super.onDestroy();
            handler.removeCallbacks(runnable);
            if (mp3Recorder != null) {
                mp3Recorder.stop();
                mp3Recorder = null;
            }
        }

        @Override
        public void onStart() {

        }

        public void startAudio() {
            handler.postDelayed(runnable, 1000);
            if (mp3Recorder == null) {
                mp3Recorder = new MP3Recorder();
            }
            try {
                mp3Recorder.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void afterRecord() {
            if (mp3Recorder != null) {
                mp3Recorder.stop();
            }

            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("filePath", mp3Recorder.getFilePath());
            hashMap.put("fileLength", recLen);
            hashMap.put("audioLength", mView.getTvAudioTime().getText().toString());

            RxBus.get().post(Constants.AUDIOCOMPLETE, JSON.toJSONString(hashMap));
            mView.dismiss();
        }

    }

}

